import {defineStore} from 'pinia'
import LoginApi from "@/common/api/login.js";

const ACCESS_TOKEN = import.meta.env.JPAAS_ACCESS_TOKEN;

export default defineStore('user', {
    state: () => {//必须是箭头函数
        return {
            passwordMode: 'default',//密码模式 (default 默认模式，md5 md5加密模式)
            token:"",
            user:""
        }
    },
    //类似组件的computed,有缓存的功能
    getters: { },
    //类似组件的methods  封装业务逻辑  修改state
    actions: {
        setPasswordMode(passwordMode){
            this.passwordMode = passwordMode ;
        },
        setToken(token){
            this.token = token ;
        },
        setUser(user){
            this.user = user ;
        },
        // 登录
        async Login(userInfo,callback) {
            try {
                LoginApi.login(userInfo).then(res => {
                    const result = res.data
                    if(result && result.accessToken && result.accessToken.access_token){
                        const timestamp = Math.round(new Date());
                        const  token={
                            value:result.accessToken.access_token,
                            expire:timestamp
                        }
                        localStorage.setItem(ACCESS_TOKEN,JSON.stringify(token) );
                        this.setToken(result.accessToken.access_token);
                    }
                    if(callback){
                        callback(res)
                    }
                }).catch(error => {
                    if(callback){
                        callback("",error)
                    }
                })
            } catch (error) {
                if(callback){
                    callback("",error);
                }
            }
        },
    }
})
